package com.hxd.otc.module.my.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.BaseActivity;
import com.hxd.otc.base.OnItemClickListener;
import com.hxd.otc.common.ApiConstants;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.common.enums.IdCardStatusEnum;
import com.hxd.otc.common.enums.RoleTypeEnum;
import com.hxd.otc.dialog.ForbiddenBankCardDialog;
import com.hxd.otc.dialog.SingBlocksDialog;
import com.hxd.otc.module.login.activity.LoginActivity;
import com.hxd.otc.module.my.adapter.ApplyBondAdapter;
import com.hxd.otc.module.my.bean.ApplyExplainContentBean;
import com.hxd.otc.module.my.bean.UploadImageBean;
import com.hxd.otc.module.my.bean.YsPreBean;
import com.hxd.otc.module.my.contract.ApplyContract;
import com.hxd.otc.module.my.presenter.ApplyPresenter;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.TitleBar;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by lzy on 2018/6/19 0019.
 * description ${申请界面}
 */
public class ApplyActivity extends BaseActivity<ApplyPresenter> implements ApplyContract.View, View.OnClickListener {

    @BindView(R.id.tv_agreement)
    TextView mTvAgreement;
    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.tv_apply)
    TextView mTvApply;
    @BindView(R.id.tv_bond)
    TextView mTvBond;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_apply_data)
    TextView mTvApplyData;
    @BindView(R.id.iv_item_logo_1)
    ImageView mIvItemLogo1;
    @BindView(R.id.tv_item_title_1)
    TextView mTvItemTitle1;
    @BindView(R.id.tv_item_desc_1)
    TextView mTvItemDesc1;
    @BindView(R.id.iv_item_logo_2)
    ImageView mIvItemLogo2;
    @BindView(R.id.tv_item_title_2)
    TextView mTvItemTitle2;
    @BindView(R.id.tv_item_desc_2)
    TextView mTvItemDesc2;
    @BindView(R.id.iv_item_logo_3)
    ImageView mIvItemLogo3;
    @BindView(R.id.tv_item_title_3)
    TextView mTvItemTitle3;
    @BindView(R.id.tv_item_desc_3)
    TextView mTvItemDesc3;
    @BindView(R.id.tv_non_inductive_silver)
    TextView mTvNonInductiveSilver;
    @BindView(R.id.tv_nor_silver)
    TextView mTvNorSilver;
    @BindView(R.id.cl_privileges)
    ConstraintLayout mClPrivileges;

    private SingBlocksDialog mDialog;
    private ApplyBondAdapter mApplyBondAdapter;
    private ForbiddenBankCardDialog<String> mSecurityCenterUIDialog;
    private static final int REQUEST_CODE_PICKER_PHOTO = 2001;

    public static final String EXTRA_YS_APPLY_PRE = "ys_apply_pre_params";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_apply;
    }

    @Override
    protected ApplyPresenter createPresenter() {
        return new ApplyPresenter(this);
    }

    @Override
    protected void initView() {
        mTitleBar.setOnTitleBarItemClickListener(new TitleBar.OnTitleBarItemClickListener() {
            @Override
            public void onBack(View v) {
                onBackPressed();
            }

            @Override
            public void onRight(View v) {
            }
        });

        updateExplain();

        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        mApplyBondAdapter = new ApplyBondAdapter(this);
        mRecyclerView.setAdapter(mApplyBondAdapter);
    }

    @Override
    protected void initData() {
        Bundle bundle = getBundle();
        if (bundle == null) {
            mPresenter.requestYsBond();
            return;
        }
        YsPreBean ysPreBean = (YsPreBean) bundle.getSerializable(EXTRA_YS_APPLY_PRE);
        mPresenter.updateYsPreBean(ysPreBean);
        mPresenter.findCardStatus();//查询身份证状态
    }

    @Override
    public void updateBond() {
        mApplyBondAdapter.addAll(true, mPresenter.getBonds(mSliverType));
    }

    @Override
    protected void initEvent() {
        mApplyBondAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                mApplyBondAdapter.setOnSelPosition(position);
            }
        });
    }

    private RoleTypeEnum mSliverType = RoleTypeEnum.NormalSliver;

    @OnClick({R.id.tv_apply, R.id.tv_agreement, R.id.tv_service, R.id.tv_apply_data, R.id.tv_nor_silver, R.id.tv_non_inductive_silver})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_apply:
                onApply();
                break;
            case R.id.tv_agreement:
                mTvAgreement.setSelected(!mTvAgreement.isSelected());
                break;
            case R.id.tv_service:
                Bundle bundle = new Bundle();
                bundle.putString(WebViewActivity.EXTRA_TITLE, getString(R.string.advertiser_agreement));
                bundle.putString(WebViewActivity.EXTRA_URL, ApiConstants.URL_OF_OTC_ADVER_APPLY);
                $startActivity(WebViewActivity.class, bundle);
                break;
            case R.id.tv_apply_data:
                onApplyData();
                break;
            case R.id.tv_nor_silver:
                onSliverTypeChange(RoleTypeEnum.NormalSliver);
                break;
            case R.id.tv_non_inductive_silver:
                onSliverTypeChange(RoleTypeEnum.NonInductiveSliver);
                break;
        }
    }

    private void onSliverTypeChange(RoleTypeEnum roleTypeEnum) {
        mSliverType = roleTypeEnum;
        mClPrivileges.setBackgroundResource(RoleTypeEnum.NonInductiveSliver.equals(mSliverType)
                ? R.drawable.shape_silver_apply_content_bg :
                R.drawable.shape_silver_apply_content_blue_bg);
        updateExplain();//更新描述说明
        updateBond();//更新保证金信息
    }

    private void updateExplain() {
        ArrayList<ApplyExplainContentBean> explainContent = mPresenter.getExplainContent(mSliverType);
        mTvItemTitle1.setText(explainContent.get(0).getTitle());
        mTvItemTitle2.setText(explainContent.get(1).getTitle());
        mTvItemTitle3.setText(explainContent.get(2).getTitle());
        mTvItemDesc1.setText(explainContent.get(0).getContent());
        mTvItemDesc2.setText(explainContent.get(1).getContent());
        mTvItemDesc3.setText(explainContent.get(2).getContent());
        mIvItemLogo1.setImageResource(explainContent.get(0).getIconResId());
        mIvItemLogo2.setImageResource(explainContent.get(1).getIconResId());
        mIvItemLogo3.setImageResource(explainContent.get(2).getIconResId());
    }

    private void onApplyData() {
        if (checkApplyPermission()) return;
        $startActivityForResult(SilverCertificationPhotoPickerActivity.class, REQUEST_CODE_PICKER_PHOTO);
    }

    private void onApply() {

        if (checkApplyPermission()) return;

        if (mApplyBondAdapter.getItems().size() == 0) {
            mPresenter.requestYsBond();
        }

        if (mApplyBondAdapter.getSelPosition() == -1) {
            showToast(getString(R.string.please_select_digital_assets_as_margin));
            return;
        }
        if (!mTvAgreement.isSelected()) {
            showToast(getString(R.string.my_please_check_agreement));
            return;
        }
        mTvApply.setOnClickListener(null);
        mPresenter.apply(mApplyBondAdapter.getItem(mApplyBondAdapter.getSelPosition()), mSliverType);
        setResult(Activity.RESULT_OK);
    }

    private boolean checkApplyPermission() {

        if (!UserHelper.isLogin()) {
            Bundle bundle = new Bundle();
            bundle.putBoolean(LoginActivity.EXTRA_FINISH_SKIP_MAIN, false);
            $startActivity(LoginActivity.class, bundle);
            return true;
        }

        if (!UserHelper.isBoundPhone()) {
            showSkipSecurityCenterUIDialog(R.string.you_have_not_bound_your_mobile_phone_number_do_you_want_to_go_to_bind_your_mobile_phone_number);
            return true;
        }

        if (IdCardStatusEnum.V1_Auditing.equals(UserHelper.getCardStatus()) && IdCardStatusEnum.V2_Auditing.equals(UserHelper.getCardStatus())) {
            showToast(getString(R.string.your_identification_is_under_review));
            return true;
        }

        if (!UserHelper.isV2Verified()) {
            showSkipSecurityCenterUIDialog(R.string.you_do_not_have_v2_authentication_yet_do_you_want_to_go_for_authentication);
            return true;
        }
        return false;
    }

    private void showSkipSecurityCenterUIDialog(int msgResId) {
        if (mSecurityCenterUIDialog == null) {
            mSecurityCenterUIDialog = new ForbiddenBankCardDialog<String>(this)
                    .setOnConfirmClickListener(new ForbiddenBankCardDialog.OnConfirmClickListener<String>() {
                        @Override
                        public void onConfirm(String data) {
                            $startActivity(SecurityCenterActivity.class);
                        }
                    });
        }
        mSecurityCenterUIDialog.setMessage(getString(msgResId))
                .show();
    }

    @Override
    public void applySuccess(String msg) {
        showToast(getString(R.string.the_certification_application_has_been_submitted_and_under_review));
        mTvApply.setOnClickListener(this);
        finish();
    }

    @Override
    public void applyFail(String errMessage, boolean showDialog) {
        mTvApply.setOnClickListener(this);

        if (!showDialog) {
            return;
        }
        //提示您当前余额不足，无法开通广告商权限
        mDialog = new SingBlocksDialog(this)
                .setTitle(getString(R.string.my_apply_dialog_title))
                .setContent(TextUtils.isEmpty(errMessage) ? getString(R.string.submit_fail) : errMessage)
                .setGotText(getString(R.string.my_apply_dialog_confirm), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mDialog != null) mDialog.dismiss();
                    }
                });
        mDialog.show();
    }

    @Override
    public void loginMiss() {
        UserHelper.logoutButNoSkipLogin();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        UIUtils.dismissDialog(mDialog);
        UIUtils.dismissDialog(mSecurityCenterUIDialog);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICKER_PHOTO && resultCode == Activity.RESULT_OK && data != null && data.hasExtra(SilverCertificationPhotoPickerActivity.RESULT_EXTRA_PHOTO_MAPS)) {
            HashMap<String, UploadImageBean> imageBeanHashMap = (HashMap<String, UploadImageBean>) data.getSerializableExtra(SilverCertificationPhotoPickerActivity.RESULT_EXTRA_PHOTO_MAPS);
            mPresenter.updateImageMap(imageBeanHashMap);
            mTvApplyData.setSelected(true);
        }
    }
}
